package web.PetStore.web.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONReader;
import sun.misc.IOUtils;
import web.PetStore.domain.Account;
import web.PetStore.domain.UrlJSON;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@WebFilter("/*")
public class AuthorityFilter extends HttpFilter {
    private UrlJSON urlJSON = new UrlJSON();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String urlPattern = req.getServletPath();
        int type = -1;
        Object get = urlJSON.json.get(urlPattern);
        if(get == null){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        type = (int) get;
        HttpSession session = req.getSession();
        Account loginUser = (Account) session.getAttribute("loginUser");
        if(loginUser == null){
            if(type == 0){
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                resp.sendRedirect("LoginForm");
            }
        }else{
            if(type == 1){
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                resp.sendRedirect("AccountForm");
            }
        }
    }
}
